package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyComment;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.query.StrategyCommentQuery;
import cn.wolfcode.wolf2w.redis.service.IStrategyRedisService;
import cn.wolfcode.wolf2w.repository.StrategyCommentRepository;
import cn.wolfcode.wolf2w.service.IStrategyCommentService;
import cn.wolfcode.wolf2w.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
	@Autowired
	private StrategyCommentRepository commentRepository;
	@Autowired
	private MongoTemplate template;
	@Autowired
	private IStrategyRedisService strategyRedisService;

	@Override
	public void addComment(StrategyComment strategyComment) {
		strategyComment.setId(null);
		strategyComment.setCreateTime(new Date());
		commentRepository.save(strategyComment);
		// 评论数+1
		strategyRedisService.replynumIncreas(strategyComment.getStrategyId());
	}

	@Override
	public void update(StrategyComment strategyComment) {
		commentRepository.save(strategyComment);
	}

	@Override
	public StrategyComment get(String id) {
		if(StringUtils.hasLength(id)){
			return commentRepository.findById(id).orElse(null);
		}
		return null;
	}

	@Override
	public Page<StrategyComment> query(StrategyCommentQuery qo) {
		Query query = new Query();
		query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
		return PageUtils.page(template, query, StrategyComment.class, qo, Sort.by(Sort.Direction.DESC,"createTime"));
	}

	@Override
	public void commentThumb(String cid, UserInfo userInfo) {
		StrategyComment strategyComment = this.get(cid);
		// 本条攻略评论的所有已点赞用户
		List<String> thumbuplist = strategyComment.getThumbuplist();
		// 当前登录用户的id
		String uid = userInfo.getId();
		// 判断本条攻略评论中的 thumbuplist 字段是否存在该id
		// 有就删除,没有就添加
		if(thumbuplist.contains(uid)){
			thumbuplist.remove(uid);
			strategyComment.setThumbupnum(strategyComment.getThumbupnum() - 1);
		}else {
			thumbuplist.add(uid);
			strategyComment.setThumbupnum(strategyComment.getThumbupnum() + 1);
		}
		this.update(strategyComment);
	}
}
